package org.cloudlab.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.cloudlab.bean.SysUser;
import org.cloudlab.common.CommonConst;
import org.cloudlab.common.ResponseResult;
import org.cloudlab.service.IUserService;
import org.cloudlab.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录相关的控制器
 *
 * @author Liu Yicong
 * @date 2023/9/5
 */
@CrossOrigin // 允许跨域访问
@RestController
@RequestMapping(value = "user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private IUserService userService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	/**
	 * 用户登录接口
	 *
	 * @param user 用户信息
	 * @return 登录信息
	 */
	@PostMapping("/login")
	public ResponseResult<Map<String, String>> login(@RequestBody SysUser user) {
		Map<String, String> map;
		try {
			String token = userService.login(user);
			map = new HashMap<>();
			map.put(CommonConst.TOKEN, token);
			map.put(CommonConst.USERNAME, user.getUserName());
			SysUser one = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, user.getUserName()));
			map.put(CommonConst.NICKNAME, one.getNickName());
			user.setLastLoginTime(new Date());
			userService.updateById(user);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}
		return ResponseResult.success("登陆成功", map);
	}

	/**
	 * 注册用户
	 *
	 * @param user 用户信息
	 * @return 注册信息
	 */
	@PostMapping("/register")
	public ResponseResult<String> register(@RequestBody SysUser user) {
		try {
			userService.register(user);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}
		return ResponseResult.success("注册成功");
	}

	@GetMapping("/userMsg")
	public ResponseResult<SysUser> getUserMsg() {
		SysUser currentUser = jwtTokenUtil.getCurrentUser();
		SysUser sysUser = new SysUser();
		sysUser.setUserName(currentUser.getUserName());
		sysUser.setNickName(currentUser.getNickName());
		return ResponseResult.success("操作成功", sysUser);
	}

	/**
	 * 用户登出
	 *
	 * @return 登出信息
	 */
	@RequestMapping("/logout")
	public ResponseResult<String> logout() {
		userService.logout();
		return ResponseResult.success();
	}
}
